<script setup lang="ts">
import type { FormInstance } from 'ant-design-vue';

import { reactive, ref, watch } from 'vue';

import {
  Button,
  Col,
  DatePicker,
  Form,
  FormItem,
  Input,
  message,
  Row,
  Select,
  Textarea,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import { createBooking, getAvailableTimeSlots } from '#/api/booking';

interface ServiceItem {
  id: string;
  name: string;
  description: string;
  price: number;
  duration: number;
  contextId: string;
  status: number;
}

interface BusinessContext {
  id: string;
  name: string;
  description: string;
  icon: string;
  status: number;
}

interface Props {
  service: ServiceItem;
  context: BusinessContext;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  bookingSubmitted: [booking: any];
}>();

const formRef = ref<FormInstance>();
const submitting = ref(false);
const availableTimeSlots = ref<any[]>([]);

const formData = reactive({
  bookingDate: undefined,
  timeSlot: null,
  customerName: '',
  phoneNumber: '',
  wechatId: '',
  memberCard: '',
  remarks: '',
});

const formRules = {
  bookingDate: [{ required: true, message: '请选择预约日期' }],
  timeSlot: [{ required: true, message: '请选择预约时段' }],
  customerName: [{ required: true, message: '请输入姓名' }],
  phoneNumber: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' },
  ],
};

// 禁用过去的日期
const disabledDate = (current: dayjs.Dayjs) => {
  return current && current < dayjs().startOf('day');
};

// 监听日期变化，加载可用时间段
watch(
  () => formData.bookingDate,
  async (newDate) => {
    if (newDate) {
      try {
        const slots = await getAvailableTimeSlots({
          serviceId: props.service.id,
          date: dayjs(newDate).format('YYYY-MM-DD'),
        });
        // 转换为Select组件需要的格式
        availableTimeSlots.value = slots
          .filter((slot) => slot.available)
          .map((slot) => ({
            label: `${slot.time} (剩余${slot.remainingCapacity}个)`,
            value: slot.time,
            disabled: slot.remainingCapacity <= 0,
          }));
      } catch (error) {
        console.error('加载时间段失败:', error);
        message.error('加载可用时间段失败');
      }
    } else {
      availableTimeSlots.value = [];
    }
    formData.timeSlot = null;
  },
);

const handleSubmit = async () => {
  try {
    submitting.value = true;

    const bookingData = {
      serviceId: props.service.id,
      contextId: props.context.id,
      bookingDate: dayjs(formData.bookingDate).format('YYYY-MM-DD'),
      timeSlot: formData.timeSlot,
      customerName: formData.customerName,
      phoneNumber: formData.phoneNumber,
      wechatId: formData.wechatId,
      memberCard: formData.memberCard,
      remarks: formData.remarks,
    };

    const result = await createBooking(bookingData);

    message.success('预约提交成功！');
    emit('bookingSubmitted', result);

    // 重置表单
    handleReset();
  } catch (error) {
    console.error('预约提交失败:', error);
    message.error('预约提交失败，请重试');
  } finally {
    submitting.value = false;
  }
};

const handleReset = () => {
  formRef.value?.resetFields();
  formData.bookingDate = undefined;
  formData.timeSlot = null;
  availableTimeSlots.value = [];
};
</script>

<template>
  <div class="booking-form">
    <Form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
      @finish="handleSubmit"
    >
      <div class="form-sections">
        <!-- 服务信息展示 -->
        <div class="service-info-section">
          <h3 class="section-title">服务信息</h3>
          <div class="service-summary">
            <div class="service-item">
              <span class="label">服务项目：</span>
              <span class="value">{{ service.name }}</span>
            </div>
            <div class="service-item">
              <span class="label">服务时长：</span>
              <span class="value">{{ service.duration }}分钟</span>
            </div>
            <div class="service-item">
              <span class="label">服务价格：</span>
              <span class="value price">¥{{ service.price }}</span>
            </div>
          </div>
        </div>

        <!-- 预约时间选择 -->
        <div class="time-selection-section">
          <h3 class="section-title">选择预约时间</h3>
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="预约日期" name="bookingDate">
                <DatePicker
                  v-model:value="formData.bookingDate"
                  :disabled-date="disabledDate"
                  placeholder="选择预约日期"
                  style="width: 100%"
                />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="预约时段" name="timeSlot">
                <Select
                  v-model:value="formData.timeSlot"
                  placeholder="选择时间段"
                  :options="availableTimeSlots"
                  style="width: 100%"
                />
              </FormItem>
            </Col>
          </Row>
        </div>

        <!-- 客户信息 -->
        <div class="customer-info-section">
          <h3 class="section-title">客户信息</h3>
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="姓名" name="customerName">
                <Input
                  v-model:value="formData.customerName"
                  placeholder="请输入姓名"
                />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="手机号" name="phoneNumber">
                <Input
                  v-model:value="formData.phoneNumber"
                  placeholder="请输入手机号"
                />
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col :span="12">
              <FormItem label="微信ID" name="wechatId">
                <Input
                  v-model:value="formData.wechatId"
                  placeholder="请输入微信ID（选填）"
                />
              </FormItem>
            </Col>
            <Col :span="12">
              <FormItem label="会员卡号" name="memberCard">
                <Input
                  v-model:value="formData.memberCard"
                  placeholder="请输入会员卡号（选填）"
                />
              </FormItem>
            </Col>
          </Row>
        </div>

        <!-- 特殊需求 -->
        <div class="special-requirements-section">
          <h3 class="section-title">特殊需求</h3>
          <FormItem label="备注" name="remarks">
            <Textarea
              v-model:value="formData.remarks"
              placeholder="请输入特殊需求或备注信息"
              :rows="3"
            />
          </FormItem>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <Button
            type="primary"
            html-type="submit"
            :loading="submitting"
            size="large"
          >
            提交预约
          </Button>
          <Button @click="handleReset" style="margin-left: 12px"> 重置 </Button>
        </div>
      </div>
    </Form>
  </div>
</template>

<style scoped>
.booking-form {
  padding: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.form-sections {
  max-width: 800px;
}

.section-title {
  padding-bottom: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  border-bottom: 2px solid #f3f4f6;
}

.service-info-section,
.time-selection-section,
.customer-info-section,
.special-requirements-section {
  margin-bottom: 32px;
}

.service-summary {
  padding: 16px;
  background: #f9fafb;
  border-radius: 8px;
}

.service-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.service-item:last-child {
  margin-bottom: 0;
}

.service-item .label {
  font-size: 14px;
  color: #6b7280;
}

.service-item .value {
  font-weight: 500;
  color: #1f2937;
}

.service-item .value.price {
  font-weight: 600;
  color: #ef4444;
}

.form-actions {
  display: flex;
  justify-content: center;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}
</style>
